package com.briup.shopadmin.web.interceptor;

import com.briup.shopadmin.common.GlobalException;
import com.briup.shopadmin.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author adam
 * @date 2023/5/15
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS") || !(handler instanceof HandlerMethod)) {
            return true;    // 静态资源直接放行
        }
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(token)) {
            throw new GlobalException(51000, "用户未登录");
        }

        try {
           JwtUtil.parseJWT(token);
        } catch (ExpiredJwtException e) {
            throw new GlobalException(51001, "token过期");
        }catch (MalformedJwtException e){
            throw new GlobalException(51001, "token非法");
        }

        log.info(request.getMethod() + "：" + request.getRequestURI() + "该请求通过");
        return true;
    }

}




